package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
	"go-zero-project/services/project/rpc/internal/config"
)

func initNaocsConfig(conf *config.NacosConfig) ([]constant.ServerConfig, constant.ClientConfig) {
	//create ServerConfig
	sc := []constant.ServerConfig{
		{
			IpAddr:      conf.Addr,
			ContextPath: conf.ContextPath,
			Port:        conf.Port,
			Scheme:      conf.Scheme,
		},
	}
	//create ClientConfig
	cc := *constant.NewClientConfig(
		constant.WithNamespaceId(conf.NamespaceId),
		constant.WithTimeoutMs(conf.TimeoutMs),
		constant.WithNotLoadCacheAtStart(conf.NotLoadCacheAtStart),
		constant.WithLogDir(conf.LogDir),
		constant.WithCacheDir(conf.CacheDir),
		constant.WithLogLevel(conf.LogLevel),
		constant.WithUsername(conf.Username),
		constant.WithPassword(conf.Password),
		constant.WithUpdateThreadNum(conf.UpdateThreadNum),
		constant.WithUpdateCacheWhenEmpty(conf.UpdateCacheWhenEmpty),
	)
	return sc, cc
}

func RegisterNacos(c config.Config) {
	sc, cc := initNaocsConfig(c.Nacos)
	options := nacos.NewNacosConfig(c.Name, c.ListenOn, sc, &cc)
	options.Group = c.Nacos.Group
	options.Weight = 1
	options.ServiceName = c.Nacos.AppName
	options.Cluster = "cluster-zwx"
	options.Metadata = map[string]string{"idc": "shanghai"}
	err := nacos.RegisterService(options)
	if err != nil {
		logx.Error(err.Error())
		return
	}
}
